package tv.youxing.android.ui;
/**
 * Created by apple on 2017/4/21.
 */

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.youxing.android.AlbumVideoBatchDownloadsActivity;
import tv.youxing.android.R;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.custom.CustomViewPager;
import tv.youxing.android.entity.AlbumInfoModel;
import tv.youxing.android.entity.AlbumVideoBatchDownloadsModel;
import tv.youxing.android.entity.DianZhanModel;
import tv.youxing.android.fragment.DynamicDetailFragment;
import tv.youxing.android.fragment.ProgramFragment;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.L;
import tv.youxing.android.utils.PicassoUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;

import static com.mob.MobSDK.getContext;

/**
 * 项目名：   youxing
 * 包名：     tv.youxing.android .ui
 * 文件名：   DynamicDetailActivity
 * 创建者：   叶克武
 * 创建时间： 2017/4/21 下午4:07
 * 描述：    TODO
 */
public class DynamicDetailActivity extends BaseActivity {


    @BindView(R.id.sub_root)
    LinearLayout llSubscribeRoot;
    @BindView(R.id.ll_subscribe)
    LinearLayout llSubscribe;//订阅
    @BindView(R.id.ivCollect)
    ImageView ivCollect;

    @BindView(R.id.ll_batch_download)
    LinearLayout llBatchDownLoad;//下载
    @BindView(R.id.riv_avatar)
    ImageView ivHead;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvTeacher)
    TextView tvTeacher;//讲师
    @BindView(R.id.tvPlayCount)
    TextView tvPlayCount;
    @BindView(R.id.tvCategory)
    TextView tvCategory;//视频类型
    @BindView(R.id.dy_status)
    TextView tvDingYeStatus;//订阅状态


    AlbumInfoModel allData;
    List<AlbumVideoBatchDownloadsModel> mAlbumVideoBatchDownloadsModels = new ArrayList<>();


    int album_id;

    private TabLayout mTabLayout;
    private CustomViewPager mViewPager;
    private List<String> mTitle;
    private List<Fragment> mFragment;


    boolean isSubscribe = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_detail);
        ButterKnife.bind(this);

        album_id = Integer.parseInt(getIntent().getStringExtra("album_id"));

        System.out.println("album_id:" + album_id);

        loadData(album_id);
    }


    void loadData(int album_id) {
        //post请求简洁版实现
        HttpParams params = new HttpParams();
//        params.put("album_id",this.album_id);
        params.put("album_id", album_id);
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(DynamicDetailActivity.this, AppConst.TOKEN, ""));


        RxVolley.post(StaticClass.albumListUrl, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                allData = GsonUtils.GsonToBean(t, AlbumInfoModel.class);

                if (allData.getCode() == AppConst.TOKENERROR) {
                    startActivity(new Intent(DynamicDetailActivity.this, LoginActivity.class));
                    finish();
                }

                initData();
                initView();
            }
        });
    }


    /**
     * 头信息
     */
    void initData() {

        AlbumInfoModel.ResultBean m = allData.getResult();



        PicassoUtils.loadImageView(this, m.getCover(), ivHead);
        tvTitle.setText(m.getName() + "");
        tvTeacher.setText("讲师: " + m.getTeacher_name().toString());
        tvPlayCount.setText("播放: " + m.getPlay_count().toString());
        tvCategory.setText("分类: " + m.getAlbum_classify_name().toString());


        if (m.getIs_order() == 1) {
            tvDingYeStatus.setText("已订阅");
            tvDingYeStatus.setTextColor(getResources().getColor(R.color.color_tagColor));
            llSubscribeRoot.setBackgroundColor(getResources().getColor(R.color.color_tagColor));
            ivCollect.setSelected(true);
            isSubscribe=true;
            llSubscribeRoot.setEnabled(false);
        } else if (m.getIs_order() == 0) {
            tvDingYeStatus.setText("订阅 " + m.getHas_play_permission());
            tvDingYeStatus.setTextColor(getResources().getColor(R.color.color_black));
            llSubscribeRoot.setBackgroundColor(getResources().getColor(R.color.color_no_tagColor));
            ivCollect.setSelected(false);
            isSubscribe=false;
            llSubscribeRoot.setEnabled(true);
        }

        mTitle = new ArrayList<>();
        mTitle.add("详情");
        mTitle.add("节目 (" + allData.getResult().getMultimedia_count() + ")");

        mFragment = new ArrayList<>();
        mFragment.add(new DynamicDetailFragment(allData));
        mFragment.add(new ProgramFragment(allData));
        initView();
    }

//    private void initData(){
//
//        mTitle = new ArrayList<>();
//        mTitle.add("详情");
//        mTitle.add("节目"+allData.getResult().getMultimedia_count());
//
//        mFragment = new ArrayList<>();
//        mFragment.add(new DynamicDetailFragment());
//        mFragment.add(new ProgramFragment());
//    }


    private void initView() {

        mTabLayout = (TabLayout) findViewById(R.id.mTabLayout);
        mViewPager = (CustomViewPager) findViewById(R.id.mViewPager);

        mViewPager.setOffscreenPageLimit(mFragment.size());

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                switch (position) {
                    case 0:

                        break;
                    case 1:

                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment getItem(int position) {
                return mFragment.get(position);
            }

            @Override
            public int getCount() {
                return mFragment.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTitle.get(position);
            }

        });

        mTabLayout.setupWithViewPager(mViewPager);

        int VIEWPAGER_DEFAULT_HEIGHT = 700;
        /*
         * ViewPager如果放到ScrollView当中，需要在Java代码中通过LayoutParams动态的
         * 设置一个固定值的高，否则ViewPager中的内容无法显示
         */
        // 1、获取屏幕密度
        float desity = getResources().getDisplayMetrics().density;
        // 2、获取ViewPager在不同屏幕密度上的手机的高度
        int viewPagerHeight = (int) (VIEWPAGER_DEFAULT_HEIGHT * desity);
        // 3、通过setLayoutParams方式，给ViewPager动态设置高度
        mViewPager.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, viewPagerHeight));

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.action_share_dynamic) {
            L.i("R.id.action_share_dynamic");
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_dynamic_detail, menu);
        return true;
    }


    @OnClick({R.id.ll_batch_download, R.id.ll_subscribe})
    public void click(View view) {

        switch (view.getId()) {
            //专辑订阅
            case R.id.ll_subscribe:
//                if (isSubscribe) {
////                    cancel_subscribe();
//                } else {
//                    click_subscribe();
//                }


                if (allData.getResult().getIs_order() == 0) {
                    click_subscribe();
                }

                break;
            case R.id.ll_batch_download:
                Intent intent = new Intent(DynamicDetailActivity.this, AlbumVideoBatchDownloadsActivity.class);

                mAlbumVideoBatchDownloadsModels.clear();
                for (int i = 0; i < allData.getResult().getMultimedia_list().size(); i++) {
                    AlbumVideoBatchDownloadsModel model = new AlbumVideoBatchDownloadsModel();
                    model.setTitle(allData.getResult().getMultimedia_list().get(i).getTitle());
                    model.setMultimedia_id(allData.getResult().getMultimedia_list().get(i).getMultimedia_id());
                    model.setPlay_url(allData.getResult().getMultimedia_list().get(i).getPlay_url());
                    model.setIcon_url(allData.getResult().getCover());
                    model.setPlay_count(allData.getResult().getMultimedia_list().get(i).getPlay_count());
                    model.setComment_count(allData.getResult().getMultimedia_list().get(i).getComment_count());
                    mAlbumVideoBatchDownloadsModels.add(model);
                }

                intent.putExtra("data", (Serializable) mAlbumVideoBatchDownloadsModels);
                startActivity(intent);
                break;

        }


    }


    //专辑订阅
    void click_subscribe() {
            HttpParams params = new HttpParams();
            params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
            params.put("album_id", allData.getResult().getAlbum_id());

            RxVolley.post(StaticClass.album_order, params, new HttpCallback() {
                @Override
                public void onSuccess(String t) {
                    DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);

                    if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                        startActivity(new Intent(DynamicDetailActivity.this, LoginActivity.class));
                        finish();
                    }

                    CustomToast.INSTANCE.showToast(dianZhanModel.getStatus());
                    if (dianZhanModel.getCode() == 200) {
                        tvDingYeStatus.setText("已订阅");
                        ivCollect.setSelected(true);
                        tvDingYeStatus.setTextColor(getResources().getColor(R.color.color_tagColor));
                        llSubscribeRoot.setBackgroundColor(getResources().getColor(R.color.color_tagColor));
                    }
                }
            });
    }


    /**
     * 取消订阅
     */
    void cancel_subscribe() {
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("album_id", allData.getResult().getAlbum_id());

        RxVolley.post(StaticClass.album_cancel, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);

                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                    startActivity(new Intent(DynamicDetailActivity.this, LoginActivity.class));
                    finish();
                }

                CustomToast.INSTANCE.showToast(dianZhanModel.getStatus());
                if (dianZhanModel.getCode() == 200) {
                    tvDingYeStatus.setText("订阅");
                    ivCollect.setSelected(false);
                    tvDingYeStatus.setTextColor(getResources().getColor(R.color.color_black));
                    llSubscribeRoot.setBackgroundColor(getResources().getColor(R.color.color_no_tagColor));
                }
            }
        });
    }
}
